package com.telecom.weixi;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.widget.ImageView;

import com.jxs.android.util.FileHloder;
import com.jxs.android.weixi.Login;
import com.telecom.weixi.util.Utils;

public class LogoActivity extends Activity {

	public LogoActivity() {
		FileHloder.createDir();
	}

	int logoDelay = 2 * 1000;
	AnimationDrawable animation;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.logo);

		ImageView imgLoading = (ImageView) findViewById(R.id.loading);
		imgLoading.setBackgroundResource(R.anim.logo_loading);
		animation = (AnimationDrawable) imgLoading.getBackground();

		new Handler().postDelayed(startRunnable, logoDelay);
	}

	@Override
	protected void onStart() {
		super.onStart();
		Debug("onStart...");
		(new Timer(false)).schedule(new AnimationTimer(animation), 100);
	}

	private static class AnimationTimer extends TimerTask {
		AnimationDrawable animation;

		public AnimationTimer(AnimationDrawable animation) {
			this.animation = animation;
		}

		@Override
		public void run() {
			animation.start();
			this.cancel();
		}
	}

	Runnable startRunnable = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			logoNext();
		}
	};

	void logoNext() {
		boolean netAvailable = Utils.isNetAvailable(this);
		if (netAvailable) {
			startApp();
		} else {
			Utils.setNetWork(this, okListener, cancelListener);
		}
	}

	private static final int REQ_NET_SETTING = 0x008;
	DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			dialog.cancel();
			startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), REQ_NET_SETTING);
		}
	};

	DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			LogoActivity.this.finish();
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQ_NET_SETTING) {
			startApp();
		}
	}

	void startApp() {
		Intent intent = new Intent(LogoActivity.this, Login.class);
		startActivity(intent);
		LogoActivity.this.finish();
	}

	void Debug(String info) {
		Log.d("test", "LogoActivity: " + info);
	}

}